import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../util/response-util";
import {RolesService} from "./roles.service";
import {Role} from "./role";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {LogUtil} from "../../../util/log-util";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {API, MsgConstants} from "../../../constants/constants";
import {TableUtil} from "../../../util/table-util";
import {MsgResult} from "../../../models/msg-result";

declare var $;

@Component({
  selector: 'app-roles',
  templateUrl: './roles.component.html'
})
export class RolesComponent implements OnInit,AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  roles: Role;

  roleIds: Array<string> = [];

  table;

  constructor(
    private router : Router,
    private route : ActivatedRoute,
    private logUtil : LogUtil,
    private tableUtil : TableUtil,
    private pageSubject : PageSubject,
    private dialogService : OneDialogService,
    private responseUtil : ResponseUtil,
    private rolesService : RolesService
  ) { }

  proxy = {
    "roleAdd": () => this.roleAdd(),
    "roleUpdate": () => this.roleUpdate(),
    "roleDelete": () => this.roleDelete(),
    "roleAuthorization": () => this.roleAuthorization(),
    "roleAssignAcc": () => this.roleAssignAcc()
  }

  ngOnInit() {
    this.pushPage();
    this.loadRoles();
  }

  /**
   * 面包屑导航
   */
  pushPage(){
    let path = new Path("权限系统","");
    this.pageSubject.pushPage("角色管理","查询",path);
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 刷新
   */
  search(){
    this.table.bootstrapTable('refresh');
  }

  /**
   * 主题查询
   */
  private loadRoles(){
    this.table = this.tableUtil.load("one_table_role",{
      columns:[
        { checkbox: true },
        { field: "roleId", title:'ID',align:'left',visible:false,switchable:false},
        { field: "roleName", title:'名称',align:'left'},
        { field: "description",title:'描述' ,align:'left'},
        { field: "creatorName",title:'创建人',align:'left', visible: false },
        { field: "create_date" ,title:'创建日期',align:'left',sortName:"CREATE_DATE",sortable:true , visible: false },
        { field: "editorName" ,title:'修改人',align:'left' , visible: false },
        { field: "modified_date" ,title:'修改日期',align:'left',sortName:"MODIFIED_DATE",sortable:true ,visible: false }
      ],
      idField:"id",
      sidePagination:'server',
      pagination:true,
      pageNumber:1,
      pageSize:15,
      pageList: [10,15, 50],
      paginationPreText:"上一页",
      paginationNextText:"下一页",
      paginationLoop:false,//是否开启循环分页
      singleSelect:false,//单选
      clickToSelect:true,//点击选中
      toolbar:"#one_operation_roles",
      url:API.rolePageListV2,
      method:'post',
      //传递附加参数
      queryParams:(params) => {
        params.roleName = $("#roleName").val();
        return params;
      },
      //返回数据处理器
      responseHandler:(result)=>{
        return this.responseUtil.bsPageHandler(result,(result)=>{
          result.data.rows.forEach(function (value) {
            value.create_date = value.createDate || '';
            value.modified_date = value.modifiedDate || '';
          });
        });
      },
      height:700,//table高度
      sortable:true,
      order:'asc',
      sortName:'MODIFIED_DATE',
      showColumns:true,//显示自定义显示列按钮
      showRefresh:true,//显示刷新按钮
      minimumCountColumns:3,//最少保留显示的列数量
      showToggle:true,//显示视图切换按钮
      showPaginationSwitch:true,//显示是否分页切换按钮
      //css
      classes:"table table-hover",
      striped:true,//隔行变色
      mobileResponsive:true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);

    // this.table = $("#one_table_role").bootstrapTable({
    //   columns:[
    //     { checkbox: true },
    //     { field: "roleId", title:'ID',align:'left',visible:false,switchable:false},
    //     { field: "roleName", title:'名称',align:'left',width: '150'},
    //     { field: "description",title:'描述' ,align:'left',width: '260'},
    //     { field: "creatorName",title:'创建人',align:'left',width: '120'},
    //     { field: "create_date" ,title:'创建日期',align:'left',sortName:"CREATE_DATE",sortable:true, width: '200'},
    //     { field: "editorName" ,title:'修改人',align:'left', width: '120', visible: false},
    //     { field: "modified_date" ,title:'修改日期',align:'left',sortName:"MODIFIED_DATE",sortable:true ,visible: false, width: '200'}
    //   ],
    //   idField:"id",
    //   sidePagination:'server',
    //   pagination:true,
    //   pageNumber:1,
    //   pageSize:15,
    //   pageList: [10,15, 50],
    //   paginationPreText:"上一页",
    //   paginationNextText:"下一页",
    //   paginationLoop:false,//是否开启循环分页
    //   singleSelect:false,//单选
    //   clickToSelect:true,//点击选中
    //   toolbar:".one-operation",
    //   url:API.rolePageListV2,
    //   method:'post',
    //   //传递附加参数
    //   queryParams:(params) => {
    //     params.roleName = $("#roleName").val();
    //     return params;
    //   },
    //   //返回数据处理器
    //   responseHandler:(result)=>{
    //     return this.responseUtil.bsPageHandler(result,(result)=>{
    //       // console.log(JSON.stringify(result));
    //       result.data.rows.forEach(function (value) {
    //         value.create_date = value.createDate || '';
    //         value.modified_date = value.modifiedDate || '';
    //       });
    //     });
    //   },
    //   height:700,//table高度
    //   sortable:true,
    //   order:'asc',
    //   sortName:'MODIFIED_DATE',
    //   showColumns:true,//显示自定义显示列按钮
    //   showRefresh:true,//显示刷新按钮
    //   minimumCountColumns:3,//最少保留显示的列数量
    //   showToggle:true,//显示视图切换按钮
    //   showPaginationSwitch:true,//显示是否分页切换按钮
    //   //css
    //   classes:"table table-hover",
    //   striped:true,//隔行变色
    //   mobileResponsive:true//响应式
    // });
  }

  /**
   * 添加按钮
   */
  roleAdd(){
    this.router.navigate(['add'],{relativeTo :this.route});
  }

  /**
   * 删除按钮
   */
  roleDelete(){
    let rows = this.table.bootstrapTable('getSelections');
    this.roleIds = this.tableUtil.getCloumns(rows,"roleId");
    if (this.roleIds.length == 0) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }

  /**
   * 确认删除
   */
  private requestDelete = () =>{
      this.rolesService.delRoles(this.roleIds).subscribe(
        result => this.responseUtil.success(result, this.processRoleDeletesResult),
        message => this.responseUtil.error(message)
      );
  }


  /**
   * 批量删除结果处理
   * @param result
   */
  processRoleDeletesResult= (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success('角色删除成功！');
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.error(result.message);
    }
  }

  /**
   * 修改按钮
   */
  private roleUpdate(){
    let rows = this.table.bootstrapTable('getSelections');
    this.roleIds = this.tableUtil.getCloumns(rows,"roleId");
    if (this.roleIds.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['update',{roleId:this.roleIds[0]}],{relativeTo :this.route});
    }
  }

  /**
   * 角色授权
   */
  roleAuthorization(){
    let rows = this.table.bootstrapTable('getSelections');
    this.roleIds = this.tableUtil.getCloumns(rows,"roleId");
    if (this.roleIds.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['authorized',{roleId:this.roleIds[0]}],{relativeTo :this.route});
    }
  }

  /**
   * 为用户分配账户
   */
  roleAssignAcc(){
    let rows = this.table.bootstrapTable('getSelections');
    this.roleIds = this.tableUtil.getCloumns(rows,"roleId");
    if (this.roleIds.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['assign',{roleId:this.roleIds[0]}],{relativeTo :this.route});
    }
  }



}
